﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Net;
using System.Threading.Tasks;


// GetTPB, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
namespace GetTpb
{
    public class ReadWebPage
    {
        private static async Task<string> GetWebPageAsync(string url)
        {
            var handler = new System.Net.Http.HttpClientHandler();
            if (handler.SupportsAutomaticDecompression)
            {
                // TPB zaczęłą używać SPDY
                handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            var httpClient = new System.Net.Http.HttpClient(handler);
            var str = await httpClient.GetStringAsync(url);
            return str;
        }

        //public static string ErrorMessage { get; private set; }
        //
        //"Could not connect to caching server 00"
        public static bool Do(string www, out string page, out string ErrorMessage)
        {
            page="";
            ErrorMessage = "";
            //
            for (int k = 0; k < 6; k++)
            {
                //
                try
                {
                    var aresult = GetWebPageAsync(www);
                    page = aresult.Result;
                    //page = await GetWebPageAsync(www);
#if false
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(www);
                    request.UserAgent = "Mozilla/5.0";//bez tego nie ściąga dyskografii z TPB [http://thepiratebay.org/search/discography/]
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    //
                    using (BufferedStream bf = new BufferedStream(response.GetResponseStream()))
                    {
                        using (StreamReader reader = new StreamReader(bf))
                        {
                            page = reader.ReadToEnd();
                        }
                    }
#endif
                }
                catch (Exception e)
                {
                    //System.Windows.Forms.MessageBox.Show(e.Message);
                    ErrorMessage = e.Message;
                    System.Threading.Thread.Sleep(2000 + k * 1500);
                    continue;
                }
                //
                //
                if (page.IndexOf("</html>", StringComparison.InvariantCulture) < 0)
                {
                    //brakuje istotnego elementu
                    ErrorMessage = "Missing tag </html>";
                    System.Threading.Thread.Sleep(2000 + k * 1500);
                    continue;
                }
                if (page.IndexOf("Problem! Please retry.", StringComparison.InvariantCulture) >= 0)
                {
                    //? Cos nie tak z TPB?
                    ErrorMessage = "Problem! Please retry.";
                    System.Threading.Thread.Sleep(2000 + k * 1500);
                    continue;
                }
                if (page.IndexOf("Service Unavailable", StringComparison.InvariantCulture) >= 0)
                {
                    //? Varnish cache server?
                    ErrorMessage = "Service Unavailable";
                    System.Threading.Thread.Sleep(2000 + k * 1500);
                    continue;
                }
                if (page.IndexOf("Search engine overloaded", StringComparison.InvariantCulture) >= 0)
                {
                    //? Search engine overloaded?
                    ErrorMessage = "Search engine overloaded";
                    System.Threading.Thread.Sleep(2000 + k * 3500);//delay 3500
                    continue;
                }
                ErrorMessage = "";
                return true;
                //
            }
            //
            return false;
        }

    }//clss
}//namespace
